using Microsoft.AspNetCore.Mvc;
using community.Models;
using System.ComponentModel.DataAnnotations;
using community.Data;
using Microsoft.EntityFrameworkCore;

namespace community.Controllers
{
    /// <summary>
    /// 物业设备查询参数
    /// </summary>
    public class PropertyEquipmentQueryDTO
    {
        /// <summary>
        /// 设备名称
        /// </summary>
        public string? Name { get; set; }

        /// <summary>
        /// 设备位置
        /// </summary>
        public string? Location { get; set; }

        /// <summary>
        /// 是否正常运行
        /// </summary>
        public bool? IsOperational { get; set; }

        /// <summary>
        /// 安装日期开始时间
        /// </summary>
        public DateTime? InstallDateStart { get; set; }

        /// <summary>
        /// 安装日期结束时间
        /// </summary>
        public DateTime? InstallDateEnd { get; set; }

        /// <summary>
        /// 每页显示数量，默认10条
        /// </summary>
        [Range(1, 100)]
        public int PageSize { get; set; } = 10;

        /// <summary>
        /// 当前页码，默认第1页
        /// </summary>
        [Range(1, int.MaxValue)]
        public int PageNumber { get; set; } = 1;
    }

    /// <summary>
    /// 创建/更新物业设备的数据模型
    /// </summary>
    public class PropertyEquipmentDTO
    {
        /// <summary>
        /// 设备名称
        /// </summary>
        [Required(ErrorMessage = "设备名称不能为空")]
        [StringLength(100, ErrorMessage = "设备名称最多100个字符")]
        public string Name { get; set; }

        /// <summary>
        /// 设备位置
        /// </summary>
        [Required(ErrorMessage = "设备位置不能为空")]
        [StringLength(200, ErrorMessage = "设备位置最多200个字符")]
        public string Location { get; set; }

        /// <summary>
        /// 安装日期
        /// </summary>
        [Required(ErrorMessage = "安装日期不能为空")]
        public DateTime InstallDate { get; set; }

        /// <summary>
        /// 是否正常运行
        /// </summary>
        public bool IsOperational { get; set; } = true;
    }

    /// <summary>
    /// 设备运行状态更新模型
    /// </summary>
    public class EquipmentStatusDTO
    {
        /// <summary>
        /// 是否正常运行
        /// </summary>
        [Required(ErrorMessage = "运行状态不能为空")]
        public bool IsOperational { get; set; }

        /// <summary>
        /// 状态变更说明
        /// </summary>
        [StringLength(500, ErrorMessage = "说明最多500个字符")]
        public string? Remark { get; set; }
    }

    /// <summary>
    /// 物业设备管理接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class PropertyEquipmentController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public PropertyEquipmentController(ApplicationDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取物业设备列表（支持分页和条件筛选）
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns>设备列表和总数</returns>
        /// <response code="200">成功获取设备列表</response>
        /// <response code="400">查询参数验证失败</response>
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> GetEquipments([FromQuery] PropertyEquipmentQueryDTO query)
        {
            var equipments = _context.PropertyEquipments.AsQueryable();

            if (!string.IsNullOrEmpty(query.Name))
                equipments = equipments.Where(e => e.Name.Contains(query.Name));

            if (!string.IsNullOrEmpty(query.Location))
                equipments = equipments.Where(e => e.Location.Contains(query.Location));

            if (query.IsOperational.HasValue)
                equipments = equipments.Where(e => e.IsOperational == query.IsOperational);

            if (query.InstallDateStart.HasValue)
                equipments = equipments.Where(e => e.InstallDate >= query.InstallDateStart);

            if (query.InstallDateEnd.HasValue)
                equipments = equipments.Where(e => e.InstallDate <= query.InstallDateEnd);

            var total = await equipments.CountAsync();

            var pagedEquipments = await equipments
                .Skip((query.PageNumber - 1) * query.PageSize)
                .Take(query.PageSize)
                .ToListAsync();

            return Ok(new {
                Total = total,
                Items = pagedEquipments
            });
        }

        /// <summary>
        /// 获取指定设备的详细信息
        /// </summary>
        /// <param name="id">设备ID</param>
        /// <returns>设备详细信息</returns>
        /// <response code="200">成功获取设备信息</response>
        /// <response code="404">指定ID的设备不存在</response>
        [HttpGet("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> GetEquipment(int id)
        {
            var equipment = await _context.PropertyEquipments.FindAsync(id);
            if (equipment == null)
                return NotFound();

            return Ok(equipment);
        }

        /// <summary>
        /// 登记新设备
        /// </summary>
        /// <param name="dto">设备信息</param>
        /// <returns>新创建的设备信息</returns>
        /// <response code="201">成功创建设备记录</response>
        /// <response code="400">提供的数据无效</response>
        [HttpPost]
        [ProducesResponseType(StatusCodes.Status201Created)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> CreateEquipment(PropertyEquipmentDTO dto)
        {
            var equipment = new PropertyEquipment
            {
                Name = dto.Name,
                Location = dto.Location,
                InstallDate = dto.InstallDate,
                IsOperational = dto.IsOperational,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            _context.PropertyEquipments.Add(equipment);
            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetEquipment), new { id = equipment.Id }, equipment);
        }

        /// <summary>
        /// 更新设备信息
        /// </summary>
        /// <param name="id">设备ID</param>
        /// <param name="dto">更新的设备信息</param>
        /// <returns>更新后的设备信息</returns>
        /// <response code="200">成功更新设备信息</response>
        /// <response code="400">提供的数据无效</response>
        /// <response code="404">指定ID的设备不存在</response>
        [HttpPut("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> UpdateEquipment(int id, PropertyEquipmentDTO dto)
        {
            var equipment = await _context.PropertyEquipments.FindAsync(id);
            if (equipment == null)
                return NotFound();

            equipment.Name = dto.Name;
            equipment.Location = dto.Location;
            equipment.InstallDate = dto.InstallDate;
            equipment.IsOperational = dto.IsOperational;
            equipment.UpdatedAt = DateTime.UtcNow;

            await _context.SaveChangesAsync();
            return Ok(equipment);
        }




        /// <summary>
        /// 新增维护
        /// </summary>
        /// <param name="id">设备ID</param>
        [HttpPatch("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> maintenanceRecord(int id)
        {
            var equipment = await _context.PropertyEquipments.FindAsync(id);
            if (equipment == null)
                return NotFound();
            equipment.UpdatedAt = DateTime.UtcNow;

            await _context.SaveChangesAsync();
            return Ok(equipment);
        }

        /// <summary>
        /// 更新设备运行状态
        /// </summary>
        /// <param name="id">设备ID</param>
        /// <param name="dto">状态信息</param>
        /// <returns>更新后的设备信息</returns>
        /// <response code="200">成功更新设备状态</response>
        /// <response code="400">提供的数据无效</response>
        /// <response code="404">指定ID的设备不存在</response>
        [HttpPatch("{id}/operational-status")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> UpdateOperationalStatus(int id, EquipmentStatusDTO dto)
        {
            var equipment = await _context.PropertyEquipments.FindAsync(id);
            if (equipment == null)
                return NotFound();

            equipment.IsOperational = dto.IsOperational;
            equipment.UpdatedAt = DateTime.UtcNow;

            await _context.SaveChangesAsync();
            return Ok(equipment);
        }

        /// <summary>
        /// 删除设备记录
        /// </summary>
        /// <param name="id">设备ID</param>
        /// <returns>无内容</returns>
        /// <response code="204">成功删除设备记录</response>
        /// <response code="404">指定ID的设备不存在</response>
        [HttpDelete("{id}")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> DeleteEquipment(int id)
        {
            var equipment = await _context.PropertyEquipments.FindAsync(id);
            if (equipment == null)
                return NotFound();

            _context.PropertyEquipments.Remove(equipment);
            await _context.SaveChangesAsync();

            return NoContent();
        }
    }
} 